package org.example.service.impl;

import org.example.mapper.AccountInfoMapper;
import org.example.model.message.AccountChangeMessage;
import org.example.service.AccountInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Service
public class AccountInfoServiceImpl implements AccountInfoService {
    private static final Logger log = LoggerFactory.getLogger(AccountInfoServiceImpl.class);

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Override
    public void addBalance(AccountChangeMessage accountChangeMessage) {
        log.info("bank2更新本地账号, 账号:{}, 金额: {}", accountChangeMessage.getAccountNo(), accountChangeMessage.getAmount());
        // 幂等校验
        int existTx = accountInfoMapper.isExistTx(accountChangeMessage.getMsgId());
        if (existTx <= 0) {
            // 执行更新
            accountInfoMapper.updateAccountBalance(accountChangeMessage.getAccountNo(), accountChangeMessage.getAmount());
            // 添加事务记录
            accountInfoMapper.addTx(accountChangeMessage.getMsgId());
            log.info("更新本地事务执行成功, 本次事务号: {}", accountChangeMessage.getMsgId());
        } else{
            log.info("更新本地事务执行失败, 本次事务号: {}", accountChangeMessage.getMsgId());
        }
    }
}
